<?php

/**
 * 删除空格/换行符
 * @param mixed $str
 * @return mixed
 */
function trimall($str)
{
    $qian = array(" ", "　", "\t", "\n", "\r");
    $hou = array("", "", "", "", "");
    return str_replace($qian, $hou, $str);
}

function getCurrentTime($format = 'Y-m-d H:i:s')
{
    return date($format, time());
}

/**
 * 根据生日获取年龄
 * @param mixed $birth
 * @return number
 */
function getAgeByBirthday($birth)
{
    if ($birth != "0000-00-00") {
        list($by, $bm, $bd) = explode('-', $birth);
        $cm = date('n');
        $cd = date('j');
        $age = date('Y') - $by - 1;
        if ($cm > $bm || $cm == $bm && $cd > $bd) $age++;
        return $age;
    } else {
        return 0;
    }
}

/**
 * 生成随机字符串
 * @param number $length
 * @return string
 */
function getRandStr($length = 5)
{
    $str = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randString = '';
    $len = strlen($str) - 1;
    for ($i = 0; $i < $length; $i++) {
        $num = mt_rand(0, $len);
        $randString .= $str[$num];
    }
    return $randString;
}

/**
 * 发送POST请求
 * @param mixed $url
 * @param mixed $post_data
 * @return string
 */
function send_post($url, $post_data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($post_data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

/**
 * post json数据
 * @param mixed $url
 * @param mixed $data_string
 * @return multitype:mixed
 */
function http_post_data($url, $data_string)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt(
        $ch,
        CURLOPT_HTTPHEADER,
        array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string)
        )
    );
    ob_start();
    curl_exec($ch);
    $return_content = ob_get_contents();
    ob_end_clean();

    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    return array($return_code, $return_content);
}

/**
 * 常规post
 * @param mixed $url
 * @param mixed $data_string
 * @return multitype:mixed
 */
function post_normal($url, $data_string)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    ob_start();
    curl_exec($ch);
    $return_content = ob_get_contents();
    ob_end_clean();
    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    return $return_content;
}

/**
 * 检查手机号码合法性
 * @param mixed $phone_num
 * @return boolean
 */
function checkPhone($phone_num)
{
    if (preg_match("/^1[23456789]\d{9}$/", $phone_num)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 验证码校验
 * @param mixed $code
 * @param string $id
 * @return boolean
 */
function check_verify($code, $id = '')
{
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}

/**
 * 控制模板中菜单的显示
 * @param rule string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
 * @param uid  int           认证用户的id
 * @param string mode        执行check的模式
 * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
 * @return boolean           通过验证返回true;失败返回false
 */
function authCheck($rule, $uid, $type = 1, $mode = 'url', $relation = 'or')
{
    $auth = new \Think\Auth();
    //获取当前uid所在的角色组id
    return $auth->check($rule, $uid, $type, $mode, $relation) ? true : false;
}

/**
 * 处理Excel中文乱码
 * @param mixed $str
 * @return string
 */
function convertUTF8($str)
{
    if (empty($str)) return '';
    return  iconv('gb2312', 'utf-8', $str);
}

/**
 * 设置时间
 * @param mixed $dt
 * @return string|mixed
 */
function checkDt($dt)
{
    if (empty($dt) || $dt == "0000-00-00 00:00:00" || $dt == "0000-00-00") {
        return null;
    } else {
        return $dt;
    }
}

/**
 * 设置时间-为空返回'-'
 * @param mixed $dt
 * @return string|mixed
 */
function checkNullDt($dt, $format = "Y-m-d H:i:s")
{
    if (empty($dt) || $dt == "0000-00-00 00:00:00" || $dt == "0000-00-00") {
        return '-';
    } else {
        return date($format, strtotime($dt));;
    }
}

/**
 * 下载文件
 * @param mixed $fileurl
 */
function downfile($fileurl, $filename)
{
    ob_start();
    $date = date("YmdHim");
    header("Content-type:application/octet-stream");
    header("Accept-Ranges:bytes");
    header("Content-Disposition:attachment;filename={$filename}");
    $size = readfile($fileurl);
    header("Accept-Length: " . $size);
}

/**
 * 格式化时间检查
 * @param mixed $dt
 * @return string
 */
function formatDt($dt, $format)
{
    if ($dt == '0000-00-00 00:00:00') {
        $dt = '-';
    } else {
        $dt = date($format, strtotime($dt));
    }
    return $dt;
}

/**
 * 根据日期获取时间详情
 * @param mixed $data 时间 格式：2016-08-31 17:26:25
 */
function getDateDetail($dates)
{
    $rtn = array();
    if ($dates == "0000-00-00 00:00:00" || $dates == "0000-00-00" || empty($dates)) {
        $rtn['year'] = 0;
        $rtn['mouth'] = 0;
        $rtn['day'] = 0;
        $rtn['hour'] = 0;
        $rtn['minute'] = 0;
        $rtn['second'] = 0;
    } else {
        $rtn['year'] = date("Y", strtotime($dates));
        $rtn['mouth'] = date("m", strtotime($dates));
        $rtn['day'] = date("d", strtotime($dates));
        $rtn['hour'] = date("H", strtotime($dates));
        $rtn['minute'] = date("i", strtotime($dates));
        $rtn['second'] = date("s", strtotime($dates));
    }
    return $rtn;
}

/**
 * 将秒（非时间戳）转化成 小时和分
 */
function secToTime($sec)
{
    $rtn = array();
    $sec = round($sec / 60);
    if ($sec >= 60) {
        $hour = floor($sec / 60);
        $min = $sec % 60;
        $rtn['hour'] = $hour;
        $rtn['minute'] = $min;
    } else {
        $rtn['hour'] = 0;
        $rtn['minute'] = $sec < 0 ? 0 : $sec;
    }
    return $rtn;
}

/**
 * 将秒（非时间戳）转化成 分钟
 */
function secToMinute($sec)
{
    $rtn = array();
    $minute = ceil($sec / 60);
    return $minute;
}

/**
 * 将秒（非时间戳）转化成 天数和小时
 * 24*60*60
 */
function secToDayAndHour($sec)
{
    $rtn = array();
    $sec = round($sec / 3600); //得到小时
    if ($sec >= 24) {
        $day = floor($sec / 24);
        $hour = $sec - $day * 24;
        $rtn['day'] = $day;
        $rtn['hour'] = $hour;
    } else {
        $rtn['day'] = 0;
        $rtn['hour'] = $sec < 0 ? 0 : $sec;;
    }
    return $rtn;
}

/**
 * 将秒（非时间戳）转化成 ** 小时 ** 分
 */
function sec2time($sec)
{
    $sec = round($sec / 60);
    if ($sec >= 60) {
        $hour = floor($sec / 60);
        $min = $sec % 60;
        $res = $hour . ' 小时 ';
        $min != 0  &&  $res .= $min . ' 分';
    } else {
        $res = $sec . ' 分钟';
    }
    return $res;
}

/**
 * 判断是视频还是语音
 * @param mixed $src 文件名称
 * @return number 1 - 语音，2-视频,， 3-amr格式语音
 */
function getVideoVoiceType($file_name)
{
    $pathinfo = pathinfo($file_name); //路径解析
    $extension = $pathinfo['extension'];
    $rtn = 0;
    switch ($extension) {
            //语音：WAV、MP3、WMA、AAC
        case 'wav':
        case "mp3":
        case "wma":
        case "aac":
            $rtn = 1;
            break;
            //视频：AVI、MOV、3GP、MP4、WMV、ASF
        case "avi":
        case "mov":
        case "3gp":
        case "mp4":
        case "wmv":
        case "asf":
            $rtn = 2;
            break;
            //语音AMR
        case "amr":
            $rtn = 3;
            break;
        default:
            break;
    }
    return $rtn;
}

/**
 * 获取文件大小M（保留一位小数）
 * @param mixed $file_path 文件地址
 * @return string
 */
function getFileSize($file_path)
{
    $file_size = filesize($file_path);
    return sprintf("%.1f", ($file_size / 1024) / 1024) . "M";
}
/**
 * 将pdf转为jpg图片
 * @return string
 */
function pdftojpg($filename, $filejpgSrc)
{
    $result = -1;
    $pdftoppmdir = \Config\ServerConfig::getConfigWithHost("pdftoppmdir"); //cjpeg命令绝对路径
    $cmd = $pdftoppmdir . " -jpeg " . $filename . ".pdf " . $filejpgSrc;
    \Think\Log::record("执行PDF转为jpg命令：" . $cmd);
    system($cmd, $result);
    \Think\Log::record("执行PDF转为jpg命令-结果：" . $result);
    return $result;
}

function getHHMMSS($str)
{
    $rtn = array();
    $rtn['t1'] = (int)(($str / 10000) == 0 ? '00' : ($str / 10000));
    if ($rtn['t1'] < 10) {
        $rtn['t1'] = '0' . $rtn['t1'];
    }
    $rtn['t2'] = (int)((($str % 10000) / 100) == 0 ? '00' : (($str % 10000) / 100));
    if ($rtn['t2'] < 10) {
        $rtn['t2'] = '0' . $rtn['t2'];
    }
    $rtn['t3'] = (int)(($str % 100) == 0 ? '00' : ($str % 100));
    if ($rtn['t3'] < 10) {
        $rtn['t3'] = '0' . $rtn['t3'];
    }
    return $rtn;
}

function ffmpegFunc($file1, $file2, $bt, $et)
{
    set_time_limit(0);
    $cmd = 'ffmpeg  -i ' . $file1 . ' -vcodec copy -acodec copy -ss ' . $bt . ' -to ' . $et . ' ' . $file2 . ' -y';
    //     $cmd = 'ffmpeg -ss ' . $bt . ' -t ' . $et . ' -i ' . $file1 . ' -vcodec copy -acodec copy ' . $file2 . ' -y';
    $result = -1;
    \Think\Log::record("调用视频剪辑工具剪辑视频命令：" . $cmd);
    system($cmd, $result); //执行命令，并将执行结果返回到$result
    if ($result != 0) {
        \Think\Log::record("调用视频剪辑工具剪辑视频返回结果：" . $result);
    }
    return $result; //成功返回 0（int）
}

/**
 * 处理特殊日期的格式
 * @param mixed $date	时间
 * @param mixed $format	格式
 * @return Ambigous <string>
 */
function getMaxDate($date, $format = 'Y-m-d H:i:s')
{
    $d = new \DateTime($date);
    return $d->format($format);
}

/**
 * 设置一周
 * @param  $type
 * author wking 20201112
 */
function getWeeks($type)
{
    $visitFlag = array(
        array("id" => "1", "name" => "周一", "checked" => 0, "bg_dt" => "", "en_dt" => ""),
        array("id" => "2", "name" => "周二", "checked" => 0, "bg_dt" => "", "en_dt" => ""),
        array("id" => "3", "name" => "周三", "checked" => 0, "bg_dt" => "", "en_dt" => ""),
        array("id" => "4", "name" => "周四", "checked" => 0, "bg_dt" => "", "en_dt" => ""),
        array("id" => "5", "name" => "周五", "checked" => 0, "bg_dt" => "", "en_dt" => ""),
        array("id" => "6", "name" => "周六", "checked" => 0, "bg_dt" => "", "en_dt" => ""),
        array("id" => "7", "name" => "周日", "checked" => 0, "bg_dt" => "", "en_dt" => ""),
    );
    if (empty($type)) {
        return $visitFlag;
    } else {
        $flaginfo = "";
        foreach ($visitFlag as $val) {
            if ($type == $val["id"]) {
                $flaginfo = $val;
                break;
            }
        }
        return $flaginfo;
    }
}
